package com.xiaoma.h5testdemo.common.utils

import android.util.Log
import android.webkit.ValueCallback
import android.webkit.WebView
import com.xiaoma.common.extend.appGlobalScope
import com.xiaoma.lib.log.KLog
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * author: liangjingbo
 * date: 2024/1/11
 * describe:
 */
object JsInjectUtils {
    private val TAG = JsInjectUtils::class.java.simpleName + "_XMTag"

    fun injectJs(webView: WebView?, jsCode: String, result: ((String?) -> Unit)? = null) {
        try {
            webView?.evaluateJavascript(jsCode
            ) { value ->
                Log.i(TAG, "onReceiveValue() value: $value")
                result?.invoke(value)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            KLog.e(TAG, "injectJs() XM_Exception: $e")
        }
    }


    fun buildLoopJsContent(id: String, valueName: String, operation: String): String {
        return "(function() {\n" +
                "  const maxAttempts = 1000;\n" +
                "  let attempts = 0;\n" +
                "  function setMarginInlineStart() {\n" +
                "    const $valueName = document.querySelectorAll('${id}');\n" +
                "\n" +
                "    if ($valueName.length > 0) {\n" +
                "      // 设置样式清除定时器\n" +
                "      $operation\n" +
                "\t  console.error('找到元素:$id');\n" +
                "      clearInterval(intervalId);\n" +
                "    } else if (attempts >= maxAttempts) {\n" +
                "      console.error('无法找到元素:$id');\n" +
                "      clearInterval(intervalId);\n" +
                "    }\n" +
                "\n" +
                "    attempts++;\n" +
                "  }\n" +
                "  const intervalId = setInterval(setMarginInlineStart, 50);\n" +
                "})();"
    }

    fun prepare(focusWebView: WebView, complete: () -> Unit) {
        appGlobalScope.launch {
            delay(1000)
            injectJs(focusWebView,
                "function checkForElements(selector, ele, fn, interval = 200, maxAttempts = 100, attempt = 1){\n" +
                        "  if(selector == 'all'){\n" +
                        "    const element = document.querySelectorAll(ele)\n" +
                        "    if(element.length > 0){\n" +
                        "      // 找到了元素\n" +
                        "      console.error('找到元素1');\n" +
                        "      fn()\n" +
                        "    }else{\n" +
                        "      // 未找到元素\n" +
                        "      console.error('未找到元素1');\n" +
                        "      checkForElements(selector, ele, interval, maxAttempts, attempt, fn)\n" +
                        "    }\n" +
                        "  }\n" +
                        "  if(selector == 'one'){\n" +
                        "    var element = document.querySelector()\n" +
                        "    if(element){\n" +
                        "      // 找到了元素\n" +
                        "      console.error('找到元素2');\n" +
                        "      fn()\n" +
                        "      setTimeout(() => {\n" +
                        "        fn()\n" +
                        "      })\n" +
                        "    }else{\n" +
                        "      // 未找到元素\n" +
                        "      console.error('未找到元素2');\n" +
                        "      checkForElements(selector, ele, interval, maxAttempts, attempt, fn)\n" +
                        "    }\n" +
                        "  }\n" +
                        "}")
            complete.invoke()
        }
    }


    fun loopInject(webView: WebView, jsCode: String, times: Int, result: String) {
        val count = times - 1
        if (count <=0) return let { Log.i(TAG, "loopInject() count == 0") }
        webView.evaluateJavascript(jsCode, ValueCallback {
            Log.i(TAG, "loopInject() it:$it result:$result")
            if (it != result) {
                appGlobalScope.launch {
                    delay(200)
                    loopInject(webView, jsCode, count, result)
                }
            }
        })
    }
}